/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2024-01-11 00:16:04
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-21 19:45:31
 */
import {
  HubConnectionBuilder,
  LogLevel,
  HubConnectionState,
} from "@microsoft/signalr";

import { emitter } from "@/helpers/emitter";
import { useAppStore } from "@/store";
import { HubEventType, HubMessage, HubMessageType } from "./types";

/**
 * signlr连接对象
 */
const connection = new HubConnectionBuilder()
  .withUrl("/api/messaging", {
    accessTokenFactory() {
      const appStore = useAppStore();
      let token = appStore.token;
      if (token) {
        return token.substring(7);
      } else {
        return "";
      }
    },
  })
  .configureLogging(LogLevel.Debug)
  .build();

const getNotificationsAsync = async () => {
  await connection.send("GetNotificationsAsync");
};

/**
 * 连接socket消息
 */
export const startConnection = async () => {
  if (connection.state == HubConnectionState.Connected) {
    return;
  }
  try {
    connection.on("ReceiveMessage", function (...args: Array<any>) {
      let data: HubMessage<any> = {
        type: args[0],
        data: args[1],
      };
      // console.log("ReceiveMessage -> data", data);
      switch (data.type) {
        case HubMessageType.Message:
          emitter.emit(HubEventType.ReceiveMessage, data);
          break;
        case HubMessageType.Notification:
          emitter.emit(HubEventType.ReceiveNotification, data);
          break;
        case HubMessageType.Notifications:
          emitter.emit(HubEventType.ReceiveNotifications, data);
          break;
        case HubMessageType.Silent:
          emitter.emit(HubEventType.ReceiveSilent, data);
          break;
        case HubMessageType.Action:
          emitter.emit(HubEventType.ReceiveAction, data);
          break;
        default:
          break;
      }
    });
    await connection.start();
    await getNotificationsAsync();
  } catch (err) {
    setTimeout(startConnection, 5000);
  }
};

/**
 * 调用方法
 * @param methodName
 * @param args
 */
export const executeMethodAsync = async (
  methodName: string,
  ...args: Array<any>
) => {
  await connection.send(methodName, ...args);
};

/**
 * 获取通知URL
 * @param item
 */
export const getNotificationUrl = (item: any) => {
  if (item.url) {
    return item.url;
  } else {
    let data = item.data ? JSON.parse(item.data) : null;
    if (item.type == 1) {
      //代办审批
      let id = data?.id || item.targetId;
      return "/workflow/todo-list?tid=" + id;
    } else if (item.type == 2) {
      //任务下发通知
      let id = data?.projectId;
      console.log(data, id, "任务下发通知");
      return "/project/members?tid=" + id;
    } else if (item.type == 4 || item.type == 3) {
      //审批完成或审批取消
      let id = data?.id || item.targetId;
      return "/workflow/my-task?tid=" + id;
    } else if (item.type == 5) {
      //审批状态变化
      let id = data?.id || item.targetId;
      return "/workflow/my-task?tid=" + id;
    }
  }
  return null;
};
